package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.adapter.ManagerDeviceAdapter;
import com.qiantu.phone.ui.dialog.BottomDeviceFilterDialog;
import com.qiantu.phone.ui.dialog.BottomDeviceDialog;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.ui.shotview.MusicShotView;
import com.qiantu.phone.ui.uiutil.LLSceneLinkageUtil;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.qiantu.phone.utils.TempDataHolder;
import com.lxj.xpopup.XPopup;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


public class DeviceActionActivity extends AppActivity{
    private android.widget.TextView selectArea;
//    private android.widget.CheckBox checkbox;
    private View btnFilter;
    private View btnAllChoose;
    private EditText mEditSearch;
    private androidx.recyclerview.widget.RecyclerView deviceList;
    private ManagerDeviceAdapter deviceAdapter;
    private SceneDetailBean sceneDetailBean;
    private LinkageBean linkageBean;
    private DeviceBean mDeviceBean;
    private BottomDeviceFilterDialog mBottomDeviceFilterDialog;
    private int mPosition;
    private int type;
    private int sceneType;
    //设备动作页面一个设备对应一个设备动作任务，当前页面重复设置同一个设备会覆盖之前动作，如需添加多个同一个设备动作任务，需要返回再次进入设备动作页面添加
    private Map<String, SceneDetailBean.SceneTaskBean> device_sceneTask = new HashMap<>();
    private Map<String, LinkageBean.LinkageTask> device_linkageTask = new HashMap<>();
    private List<DeviceBean> allDevices;
    private Boolean isAllSelect = false;

    Map<String,Integer> taskData = new HashMap<>();
    private BottomListDialog mBottomListDialog;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_action;
    }

    @Override
    protected void initView() {
        mPosition = getInt("position", -1);
        type = getInt("type");
        sceneType = getInt("sceneType", 1);
        taskData = (Map<String, Integer>) getIntent().getSerializableExtra("taskData");
        mEditSearch = findViewById(R.id.edit_search);
        selectArea = findViewById(R.id.select_area);
//        checkbox = findViewById(R.id.checkbox);
        btnFilter = findViewById(R.id.btn_filter);
        btnAllChoose = findViewById(R.id.btn_all_choose);
        deviceList = findViewById(R.id.device_list);
        setOnClickListener(R.id.btn_filter,R.id.btn_all_choose);
        mEditSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0){
                    searchDevice(s.toString());
                }else{
                    if(mBottomDeviceFilterDialog == null){
                        getLocalDevices();
                    }else{
                        loadSelectedDevices();
                    }
                }
            }
        });
    }

    private void loadSelectedDevices(){
        showDialog();
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                List<DeviceBean> devices = mBottomDeviceFilterDialog.getAllDeviceFormSelectArea();
                emitter.onNext(devices);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        deviceAdapter.setTotalData(devices);
                        hideDialog();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

    private void searchDevice(String keywords){
        if(allDevices != null){
            List<DeviceBean> searchDevices = new ArrayList<>();
            for(DeviceBean deviceBean : allDevices){
                if(deviceBean.getName() != null && deviceBean.getName().contains(keywords)){
                    searchDevices.add(deviceBean);
                }
            }
            deviceAdapter.setTotalData(searchDevices);
        }
    }

    @Override
    protected void initData() {
        sceneDetailBean = TempDataHolder.getEditSceneDetailBean(sceneType);
        linkageBean = LinkageDataHolder.getLinkageData();
        deviceList.setLayoutManager(new GridLayoutManager(getContext(), 2));
        deviceAdapter = new ManagerDeviceAdapter(getContext(),taskData);
        deviceAdapter.setIsDeviceAction(true);
        deviceList.setAdapter(deviceAdapter);
        deviceAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                mDeviceBean = deviceAdapter.getData().get(position);
                boolean isAdd = !deviceAdapter.isSelected(mDeviceBean);
                showDeviceDialog(isAdd);
            }
        });
        deviceAdapter.setOnChildClickListener(R.id.btn_delete_device_action, new BaseAdapter.OnChildClickListener() {
            @Override
            public void onChildClick(RecyclerView recyclerView, View childView, int position) {
                DeviceBean device = deviceAdapter.getData().get(position);
                deviceAdapter.removeSelected(device.getDeviceSerialNo());
                if (type == AddTaskActivity.TYPE_SCENE) {
                    SceneDetailBean.SceneTaskBean addTask = device_sceneTask.get(device.getDeviceSerialNo());
                    if(addTask == null){
                        return;
                    }
                    device_sceneTask.remove(device.getDeviceSerialNo());
                    for (SceneDetailBean.SceneTaskBean sceneTask : sceneDetailBean.getSceneTasks()) {
                        if(addTask.getSceneTaskSerialNo().equals(sceneTask.getSceneTaskSerialNo())){
                            sceneDetailBean.getSceneTasks().remove(sceneTask);
                            break;
                        }
                    }
                } else if (type == AddTaskActivity.TYPE_LINKAGE) {
                    LinkageBean.LinkageTask addTask = device_linkageTask.get(device.getDeviceSerialNo());
                    if(addTask == null){
                        return;
                    }
                    device_linkageTask.remove(device.getDeviceSerialNo());
                    for (LinkageBean.LinkageTask linkageTask : linkageBean.getLinkageTasks()) {
                        if(addTask.getTaskSerialNo().equals(linkageTask.getTaskSerialNo())){
                            linkageBean.getLinkageTasks().remove(linkageTask);
                            break;
                        }
                    }
                }
                checkRightButtonState();
                checkAllSelect();
            }
        });
        getTitleBar().getRightView().setEnabled(false);
        getLocalDevices();
    }


    private void getLocalDevices(){
        showDialog();
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                List<DeviceBean> devices = LLDeviceDBManager.getInstance(getContext()).getActionDevices();
                emitter.onNext(devices);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        hideDialog();
                        allDevices = devices;
                        deviceAdapter.setTotalData(devices);
//                        selectArea.setText(getString(R.string.all_device_count_holder, devices.size()));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

    @Override
    public void onRightClick(View view) {
        if (type == AddTaskActivity.TYPE_SCENE) {
            switch (sceneType){
                case 1:
                    startActivity_SingleTask(EditSceneActivityNew.class);
                    break;
                case 3:
                    startActivity_SingleTask(EditSceneIntentActivity.class);
                    break;
                case 4:
                    startActivity_SingleTask(EditScenePrivateActivity.class);
                    break;
            }
        } else if (type == AddTaskActivity.TYPE_LINKAGE) {
            startActivity_SingleTask(EditLinkageActivity.class);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.checkbox:
//                deviceAdapter.setOnlySeeCommonly(checkbox.isChecked());
//                String text = (String) selectArea.getText();
//                selectArea.setText(text.split(" ")[0] + " (" + deviceAdapter.getItemCount() + ")");
//                break;
            case R.id.btn_filter:
                showBottomDeviceFilterDialog();
                break;
            case R.id.btn_all_choose:
//                showSelectAreaDialog(view);
                touchAllSelectButton();
                break;
        }
    }

    public void touchAllSelectButton(){
        isAllSelect = !isAllSelect;
        if(!isAllSelect){
            if (type == AddTaskActivity.TYPE_SCENE) {
                for(int i = 0; i < deviceAdapter.getData().size();i++){
                    DeviceBean deviceBean = deviceAdapter.getItem(i);
                    device_sceneTask.remove(deviceBean.getDeviceSerialNo());
                    deviceAdapter.removeSelected(deviceBean.getDeviceSerialNo());
                }
            } else if (type == AddTaskActivity.TYPE_LINKAGE) {
                for(int i = 0; i < deviceAdapter.getData().size();i++){
                    DeviceBean deviceBean = deviceAdapter.getItem(i);
                    device_linkageTask.remove(deviceBean.getDeviceSerialNo());
                    deviceAdapter.removeSelected(deviceBean.getDeviceSerialNo());
                }
            }
            checkRightButtonState();
        }else{
            showBottomListDialog();
        }
        btnAllChoose.setSelected(isAllSelect);
    }

    private void checkRightButtonState(){
        if(deviceAdapter.getSelectedSize() > 0){
            getTitleBar().getRightView().setEnabled(true);
        }else{
            getTitleBar().getRightView().setEnabled(false);
        }
    }

    private void showBottomDeviceFilterDialog() {
        if (mBottomDeviceFilterDialog == null) {
            mBottomDeviceFilterDialog = new BottomDeviceFilterDialog(getContext(), BottomDeviceFilterDialog.TYPE_DEVICE, BottomDeviceFilterDialog.ACTION_DEVICE) {
                @Override
                public void onConfirm(boolean hasFilter, List<DeviceBean> result) {
                    btnFilter.setSelected(hasFilter);
                    deviceAdapter.setTotalData(result);
                    checkAllSelect();
                }
            };
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(false)
                    .asCustom(mBottomDeviceFilterDialog);
        }
        mBottomDeviceFilterDialog.setInitCount(deviceAdapter.getItemCount());
        List<FloorBean> floors = LLFloorDBManager.getInstance(getContext()).getNotEmptyRoomFloors();
        mBottomDeviceFilterDialog.setFloorBeans(floors);
        mBottomDeviceFilterDialog.show();
    }

    private void allSelect(Boolean isOn){
        for(int i =0;i <deviceAdapter.getData().size();i++){
            DeviceBean deviceBean = deviceAdapter.getData().get(i);
            Map<String, String> statusJson = new LinkedHashMap<>();
            if(deviceBean.getType().equals("curtain")){
                statusJson.put("strokepercentage",isOn ?  "100" : "0");
            }else if(deviceBean.getType().equals("wireless_315")){
                statusJson.put("wirelessctrl_315",isOn ?  "1" : "1");
            }else if(deviceBean.getType().equals("wireless_433")){
                statusJson.put("wirelessctrl_433",isOn ?  "1" : "1");
            }else if(deviceBean.getType().equals("infrared")){
                statusJson.put("irctrl",isOn ?  "1" : "1");
            }else if(deviceBean.getDeviceType().equals("xinyue_music")){
                statusJson.put("playstate",isOn ?  "1" : "0");
            }else if(deviceBean.getType().equals("universal")){
                continue;
            }else{
                statusJson.put("power",isOn ?  "1" : "0");
            }

            if (type == AddTaskActivity.TYPE_SCENE) {
                if(!device_sceneTask.containsKey(deviceBean.getDeviceSerialNo())){
                    SceneDetailBean.SceneTaskBean taskBean = LLSceneLinkageUtil.addDeviceInstruct(sceneDetailBean, deviceBean, statusJson, mPosition);
                    taskBean.setSort(i);
                    device_sceneTask.put(deviceBean.getDeviceSerialNo(), taskBean);
                    deviceAdapter.checkSelected(deviceBean);
                }
            } else if (type == AddTaskActivity.TYPE_LINKAGE) {
                if(!device_linkageTask.containsKey(deviceBean.getDeviceSerialNo())){
                    LinkageBean.LinkageTask task = LLSceneLinkageUtil.addDeviceInstruct(linkageBean, deviceBean, statusJson, mPosition);
                    task.setSort(i);
                    device_linkageTask.put(deviceBean.getDeviceSerialNo(), task);
                    deviceAdapter.checkSelected(deviceBean);
                }
            }
        }
        checkRightButtonState();
        checkAllSelect();
    }

    private void checkAllSelect(){
        for(int i =0;i <deviceAdapter.getData().size();i++){
            DeviceBean deviceBean = deviceAdapter.getData().get(i);
            Boolean flag = true;
            if (type == AddTaskActivity.TYPE_SCENE) {
                if(!device_sceneTask.containsKey(deviceBean.getDeviceSerialNo())){
                    btnAllChoose.setSelected(false);
                    return;
                }
            } else if (type == AddTaskActivity.TYPE_LINKAGE) {
                if(!device_linkageTask.containsKey(deviceBean.getDeviceSerialNo())){
                    btnAllChoose.setSelected(false);
                    return;
                }
            }
        }
        btnAllChoose.setSelected(true);
    }

    private SceneDetailBean.DeviceItemStateDataBean getSceneDeviceStateData(){
        SceneDetailBean.SceneTaskBean sceneTask = device_sceneTask.get(mDeviceBean.getDeviceSerialNo());
        if(sceneTask == null){
            return null;
        }
        SceneDetailBean.SceneDeviceInstructBean sceneDeviceInstruct = sceneTask.getSceneDeviceInstruct();
        if(sceneDeviceInstruct != null){
            return sceneDeviceInstruct.getDeviceItemStateData();
        }
        return null;
    }

    private LinkageBean.LinkageTask.DeviceStateDataDTO getLinkageDeviceStateData(){
        LinkageBean.LinkageTask linkageTask = device_linkageTask.get(mDeviceBean.getDeviceSerialNo());
        if(linkageTask == null){
            return null;
        }
        return linkageTask.getDeviceStateData();
    }

    private BottomDeviceDialog mDeviceDialog;

    private void showDeviceDialog(boolean isAdd) {
        mDeviceDialog = new BottomDeviceDialog(this) {
            @Override
            public void onSave(Map<String, String> statusJson,List<DeviceBean> deviceBeans) {
                getTitleBar().getRightView().setEnabled(true);
                deviceAdapter.checkSelected(mDeviceBean);
                if (type == AddTaskActivity.TYPE_SCENE) {
                    if(isAdd){
                        SceneDetailBean.SceneTaskBean task = LLSceneLinkageUtil.addDeviceInstruct(sceneDetailBean, mDeviceBean, statusJson, mPosition);
                        device_sceneTask.put(mDeviceBean.getDeviceSerialNo(), task);
                        if(deviceBeans != null){
                            for(int i =0;i <deviceBeans.size();i++){
                                DeviceBean deviceBean = deviceBeans.get(i);
                                SceneDetailBean.SceneTaskBean taskBean = LLSceneLinkageUtil.addDeviceInstruct(sceneDetailBean, deviceBean, statusJson, mPosition);
                                device_sceneTask.put(deviceBean.getDeviceSerialNo(), taskBean);
                                deviceAdapter.checkSelected(deviceBean);
                            }
                        }
                    }else{
                        SceneDetailBean.DeviceItemStateDataBean deviceStateData = getSceneDeviceStateData();
                        if(deviceStateData != null){
                            deviceStateData.setStatus(statusJson);
                        }
                    }
                } else if (type == AddTaskActivity.TYPE_LINKAGE) {
                    if(isAdd) {
                        LinkageBean.LinkageTask task = LLSceneLinkageUtil.addDeviceInstruct(linkageBean, mDeviceBean, statusJson, mPosition);
                        device_linkageTask.put(mDeviceBean.getDeviceSerialNo(), task);
                        if(deviceBeans != null){
                            for(int i =0;i <deviceBeans.size();i++){
                                DeviceBean deviceBean = deviceBeans.get(i);
                                LinkageBean.LinkageTask taskBean = LLSceneLinkageUtil.addDeviceInstruct(linkageBean, deviceBean, statusJson, mPosition);
                                device_linkageTask.put(deviceBean.getDeviceSerialNo(), taskBean);
                                deviceAdapter.checkSelected(deviceBean);
                            }
                        }
                    }else{
                        LinkageBean.LinkageTask.DeviceStateDataDTO deviceStateData = getLinkageDeviceStateData();
                        if(deviceStateData != null) {
                            deviceStateData.setStatus(statusJson);
                        }
                    }
                }
                checkAllSelect();
            }
        };
        Map<String, String> actMap = null;
        if (type == AddTaskActivity.TYPE_SCENE) {
            SceneDetailBean.DeviceItemStateDataBean deviceStateData = getSceneDeviceStateData();
            if(deviceStateData != null){
                actMap = deviceStateData.getStatus();
            }
        } else if (type == AddTaskActivity.TYPE_LINKAGE) {
            LinkageBean.LinkageTask.DeviceStateDataDTO deviceStateData = getLinkageDeviceStateData();
            if(deviceStateData != null){
                actMap = deviceStateData.getStatus();
            }
        }
        new XPopup.Builder(this)
                .dismissOnBackPressed(true)
                .enableDrag(false)
                .asCustom(mDeviceDialog);
        mDeviceDialog.setAcitity(getAppActivity());
        mDeviceDialog.setDeviceBean(mDeviceBean, actMap);
        mDeviceDialog.setIsEdit(true);
        mDeviceDialog.show();
    }

    private void showBottomListDialog(){
        if (mBottomListDialog == null) {
            mBottomListDialog = new BottomListDialog(this);
            mBottomListDialog.setDialogClickListener(new BottomListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(this);
            List<String> data = new ArrayList<>();
            data.add("开");
            data.add("关");
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    allSelect(position == 0);
                    mBottomListDialog.dismiss();
                }
            });
            mBottomListDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomListDialog);
        }
        ListLabelAdapter listLabelAdapter = (ListLabelAdapter) mBottomListDialog.getAdapter();
        listLabelAdapter.setChecekSelect(true);
        mBottomListDialog.show();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MusicShotView.requCode){
            if (resultCode== Activity.RESULT_OK){
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("songname",data.getStringExtra("musicName"));
                    jsonObject.put("songpicurl",data.getStringExtra("picUrl"));
                    jsonObject.put("musicid",data.getStringExtra("musicid"));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
                mDeviceDialog.setMusicID_dialog(jsonObject);
            }
        }
    }
}